#!/bin/bash -e

#set -o xtrace

help () {
  echo "Usage: $0 <\"csv\"|\"csv1\"|\"csv2\"|\"csv3\">"
  exit 1
}

if [ $# -lt 1 ]; then
  help
fi

measure_tool=$(pwd)/csv-measure.py

csv_subtype="$1"
case "$csv_subtype" in
"csv")
  ;;
"csv1")
  ;;
"csv2")
  ;;
"csv3")
  ;;
*)
  help
  ;;
esac

kata_assets_dir=/opt/kata/share/kata-containers/

ovmf_path=${kata_assets_dir}/DUMMY_OVMF
kernel_path=${kata_assets_dir}/DUMMY_BZIMAGE
initrd_path=${kata_assets_dir}/DUMMY_INITRD
cmdline_path=$(mktemp /tmp/cmdline.csv1_2_3.XXXXXXXX)

vcpu_model="Dhyana"
nr_vcpus=0
duration=$((SECONDS+30))
append=""

dbg () {
  echo -e "\033[32m"
  echo $*
  echo -e "\033[0m"
}

while [ $SECONDS -lt $duration ]; do
  qemu_process=$(ps aux | grep qemu | grep append || true)
  if [ -n "${qemu_process}" ]; then
    ovmf_path=$(echo ${qemu_process} \
      | sed "s|.*\(if=pflash,.*$\)|\1|g" \
      | sed "s| -.*$||" \
      | sed "s|.*file=\(.*$\)|\1|" \
      | sed "s|,readonly=on||")
    kernel_path=$(echo ${qemu_process} \
      | sed "s|.*-kernel \(.*$\)|\1|g" \
      | sed "s| -.*$||")
    initrd_path=$(echo ${qemu_process} \
      | sed "s|.*-initrd \(.*$\)|\1|g" \
      | sed "s| -.*$||")
    append=$(echo ${qemu_process} \
      | sed "s|.*-append \(.*$\)|\1|g" \
      | sed "s| -.*$||")
    echo "${append}" | tee $cmdline_path

    vcpu_model=$(echo ${qemu_process} \
      | sed 's|.*-cpu \(.*$\)|\1|g' \
      | sed "s| -.*$||" \
      | sed "s|,.*$||")
    nr_vcpus=$(echo ${qemu_process} \
      | sed "s|.* -smp \([0-9]*\).*|\1|")
    break
  fi
  sleep 1
done

dbg "OVMF => ${ovmf_path}"
dbg "KERNEL => ${kernel_path}"
dbg "INITRD => ${initrd_path}"
dbg "CMDLINE => ${cmdline_path}"
dbg "VCPU_MODEL => ${vcpu_model}"
dbg "VCPUS => ${nr_vcpus}"

if [ "$csv_subtype" == "csv3" ]; then
measurement=$(python3 ${measure_tool} \
     --ovmf "${ovmf_path}" \
     --kernel "${kernel_path}" \
     --initrd "${initrd_path}" \
     --cmdline "${cmdline_path}" \
     --csv3 \
     --vcpumodel "${vcpu_model}" \
     --smp ${nr_vcpus}
     )
else
measurement=$(python3 ${measure_tool} \
     --ovmf "${ovmf_path}" \
     --kernel "${kernel_path}" \
     --initrd "${initrd_path}" \
     --cmdline "${cmdline_path}"
     )
fi
dbg "MEASUREMENT => ${measurement}"

rm $cmdline_path
